package com.jiangyg.devtools.ui;

import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextArea;
import com.jiangyg.devtools.base.Checker;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import javax.swing.border.CompoundBorder;

/**
 * 类描述：代码文本域
 *
 * @author jiangyg
 * @date 2023-08-15
 */
public class CodeTextArea extends JBScrollPane implements Checker {

    /**
     * 是否必填
     */
    private boolean required;

    private final JBTextArea textArea = new JBTextArea();

    public CodeTextArea() {
        super();

        initProps();

        initBorder();
    }

    public CodeTextArea(boolean required) {
        this();
        this.required = required;
    }

    public String getText() {
        return this.textArea.getText();
    }

    public void setText(String text) {
        this.textArea.setText(text);
    }

    /**
     * 功能描述：初始化属性
     */
    private void initProps() {
        this.setViewportView(textArea);
        this.setVisible(true);
        this.getVerticalScrollBar().setUnitIncrement(15);
        this.getVerticalScrollBar().setDoubleBuffered(true);
    }

    /**
     * 功能描述：初始化边框
     */
    private void initBorder() {
        final CompoundBorder border = BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(2, 2, 2, 2),
                BorderFactory.createEmptyBorder(8, 8, 8, 8));
        textArea.setBorder(border);
    }

    public void setRequired(boolean required) {
        this.required = required;
    }

    @Override
    public boolean check() {
        if (required && StringUtils.isBlank(getText())) {
            final CompoundBorder border = BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(JBColor.RED, 2),
                    BorderFactory.createEmptyBorder(8, 8, 8, 8));
            textArea.setBorder(border);
            return false;
        }
        initBorder();
        return true;
    }

}
